<?php

namespace app\admin\controller\coll;

use app\common\controller\Backend;
use app\common\model\coll\Analysis;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Collection extends Backend
{
    
    /**
     * Collection模型对象
     * @var \app\common\model\coll\Collection
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\coll\Collection;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['storehouse','pay'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['storehouse','pay'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            $houses = Db::name('storehouse')->select();
            foreach ($list as $row) {
                $row->visible(['id','paymoney','is_income','createtime','operator','company','settle_name','storehouse_id','pay_time','pay_id','status','make_time','discount']);
                $row->visible(['storehouse']);
                $row->getRelation('storehouse')->visible(['name']);
                $row->visible(['pay']);
                $row->getRelation('pay')->visible(['name']);
            }
            $list = collection($list)->toArray();
            $status = $this->model->getstatus();
            $types  = $this->model->gettype();
            foreach ($list as $k=> $v){
                foreach ($houses as $val){
                    if($val['id'] == $v['storehouse_id']){
                        $list[$k]['storehouse_id'] = $val['name'];
                    }
                }
                $list[$k]['ystatus'] = $v['status'];
                $list[$k]['status'] = $status[$v['status']];
                $list[$k]['is_income'] = $types[$v['is_income']];
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function getconfig(){
        $state = input('state/d',0);
        switch ($state){
            case 1:
                return array(
                  1=>'收入',
                  2=>'支出',
                );
                break;
            case 2:
                return $this->model->getstatus();
                break;
            case 3:
                return $this->model->gettype();
                break;
            case 4:
                $list = Db::name('analysis_pay')->select();
                $arr = [];
                foreach ($list as $v){
                    $arr[] = $v['name'];
                }
                return $arr;
                break;
        }
    }
    public function detail($ids = null){
        $row = $this->model->find($ids);
        if(empty($row)){
            $this->error('数据不存在');
        }


        $houses = Db::name('storehouse')->select();
        $list = Db::name('analysis_log')
            ->field('l.*,a.source,a.number,a.cost')
            ->alias('l')
            ->join('analysis a','l.analysis_id = a.id')
            ->where(array('analysis_collection_id'=>$ids))
            ->select();
        $source = dill_type();
        $allcost = 0;
        $allpaymoney = 0;

        $logids = [];

        foreach ($list as  $k => $v){
            foreach ($houses as $val){
                if($val['id'] == $v['storehouse_id']){
                    $list[$k]['house_name'] = $val['name'];
                }
            }
            $list[$k]['source'] = $source[$v['source']];
            $allcost+=$v['cost'];
            $allpaymoney+=$v['price'];
            $logids[] = $v['analysis_id'];
        }
        //其他时候收的钱
        $otherprice = Db::name('analysis_log')->where(array('analysis_id'=>array('in',$logids),'analysis_collection_id'=>array('neq',$ids),'status'=>1))->sum('price');

        $this->assign('ids',$ids);
        $this->assign('otherprice',$otherprice);
        $this->assign('list',$list);
        $paymodel = new \app\common\model\coll\Pay();
        $plist = $paymodel->where(array('status'=>'normal'))->select();
        $this->assign('plist',$plist);
        $this->assign('row',$row);
        $this->assign('allcost',$allcost);
        $this->assign('allpaymoney',$allpaymoney);
        $this->assign('syprice',bcsub(bcsub(bcsub($allcost,$allpaymoney,2),$otherprice,2),$row['discount'],2));
        return $this->view->fetch();
    }
    public function cancelbill($ids = null){
        $row = $this->model->find($ids);
        if(empty($row)){
            $this->error('数据不存在');
        }
        if($row['status'] !=1){
            $this->error('状态异常');
        }
        $reason = input('reason');
        $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
        Db::startTrans();
        try {
            $this->model->save(array('status' => 2), array('id' => $ids));//修改单据状态
            $res =Db::name('cancel_bill')
                ->insert(array(
                    'reason' => $reason,
                    'source' => 17,
                    'admin_id' => session('admin')['id'],
                    'group_id' => $group['group_id'],
                    'company' => $group['name'],
                    'operator' => session('admin')['nickname'],
                    'controller' => 'coll/collection',
                    'source_id' => $row['id'],
                    'number' => isset($row['number'])?$row['number']:'',
                    'createtime' => time(),
                ));
            Db::name('examine_log')->insert(array(
                'admin_id'=>session('admin')['id'],
                'type'=>3,
                'createtime'=>time(),
                'controller'=>'coll/collection',
                'source_id'=>$ids,
                'source'=>17,
                'remark'=>'收款单',
                'number'=>isset($row['number'])?$row['number']:'',
            ));

            $logs = Db::name('analysis_log')->where(array('analysis_collection_id'=>$ids))->select();
            foreach ($logs as $v){
                Db::name('analysis_log')->where(array('id'=>$v['id']))->update(array('status'=>2));
                $count = Db::name('analysis_log')->where(array('analysis_id'=>$v['analysis_id']))->where('status',1)->count();
                if($count > 0){
                    $analysis = new Analysis();
                    $analysis->save(array('status'=>2),array('id'=>$v['analysis_id']));
                }else{
                    $analysis = new Analysis();
                    $analysis->save(array('status'=>1),array('id'=>$v['analysis_id']));
                }
            }

            Db::commit();
            return array(
                'code'=>1,
                'msg'=>'操作成功'
            );
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        $params = input('row/a');
        if(empty($params['price'])){
            $this->error('金额不能为空');
        }

        if(empty($params['thumb']) && empty($params['remark'])){
            $this->error('凭证或备注至少选一项');
        }
    }
    public function countget()
    {
        $where = [];
        $id = input('id/d',0);
        if(!empty($id)){
            $where['id'] = $id;
        }
        $is_income = input('is_income/d',0);
        if(!empty($is_income)){
            $where['is_income'] = $is_income;
        }
        $createtime = input('createtime',0);
        if(!empty($createtime)){
            $time = explode(' - ',$createtime);
            $where['createtime'] = array('between time',$time);;
        }
        $operator = input('operator',0);
        if(!empty($operator)){
            $where['operator'] = array('like','%'.$operator.'%');;
        }
        $settle_name = input('settle_name',0);
        if(!empty($settle_name)){
            $where['settle_name'] = array('like','%'.$settle_name.'%');
        }
        $storehouse_name = input('storehouse_name',0);
        if(!empty($storehouse_name)){
            $srow = Db::name('storehouse')->where(array('name'=>$storehouse_name))->find();
            if(!empty($srow)){
                $where['storehouse_id'] = $srow['id'];
            }
        }
        $pay_name = input('pay_name',0);
        if(!empty($pay_name)){
            $prow = Db::name('analysis_pay')->where(array('name'=>$pay_name))->find();
            if(!empty($prow)){
                $where['pay_id'] = $prow['id'];
            }
        }
        $pay_time = input('pay_time',0);
        if(!empty($pay_time)){
            $time = explode(' - ',$createtime);
            $where['pay_time'] = array('between time',$time);;
        }
        $make_time = input('make_time',0);
        if(!empty($make_time)){
            $time = explode(' - ',$createtime);
            $where['make_time'] = array('between time',$time);;
        }
        $price = $this->model->where($where)->sum('paymoney');
        return array(
          'price'=>$price,
        );
    }
}
